<?php
namespace app\bbs\controller;
use x\Xbase;
class Qq extends Xbase
{
    public $qq;
    public function __construct(){
        parent::__construct();
        $callbackUrl = url('qq/reback');
        $this->qq = new \Yurun\OAuthLogin\QQ\OAuth2(c('api.qq_connect_appid'), c('api.qq_connect_appkey'), $callbackUrl);
    }
    /**
     * qq快捷登录
     * @return [type] [description]
     */
    public function login(){
        // 获取登录授权跳转页地址
        $url = $this->qq->getAuthUrl();
        // 存储sdk自动生成的state，回调处理时候要验证
        cookie('YURUN_QQ_STATE', $this->qq->state);
        // 跳转到登录页
        header('location:' . $url);
    }

    /**
     * qq登录回调, 自动登录系统
     * @return [type] [description]
     */
    public function reback(){
        // 获取accessToken，把之前存储的state传入，会自动判断。获取失败会抛出异常！
        $accessToken = $this->qq->getAccessToken(cookie('YURUN_QQ_STATE'));
        // openid，用户在第三方平台的唯一标识
        $openid = $this->qq->getOpenID($accessToken);
        // 获取用户资料，第一个参数不传则默认使用getAccessToken方法获取到的结果
        $user = $this->qq->getUserInfo();
        $rs = $this->db->query("select * from user where qq_openid=?",[$openid],1);
        //已注册过了
        if(!$rs){
            $data = [
                'username' => $user['nickname'],
                'qq_openid' => $openid,
                'sex' => $user['gender']=='男'?1:0,
                'pic' => $user['figureurl_qq_2'],
                'province' => $user['province'],
                'city' => $user['city'],
                'reg_ip' => ip(),
                'create_time' => time(),
            ];
            $id = $this->db->insert('user',$data);
            $rs = $this->db->find('user',$id);
        }
        if($rs){
            //自动登录
            m('user','c')->recordLogin($rs);
        }
        r(url('tie/init'));
    }
}
